
import React, { useState, useCallback } from 'react';
import { Button, Panel } from './shared';
import { PlayIcon, TrashIcon } from './icons';

const MOCK_DB_RESPONSE = [
    { point_code: 'wg01', point_type: 'wg', url: '2025-03-04/5377c1f3.jpg' },
    { point_code: 'wg02', point_type: 'wg', url: '2025-03-04/a2b4c6d8.jpg' },
    { point_code: 'ng01', point_type: 'ng', url: '2025-03-05/e9f8g7h6.jpg' },
];

interface GenerateJsonViewProps {
  setStatusMessage: (message: string) => void;
}

const GenerateJsonView = ({ setStatusMessage }: GenerateJsonViewProps) => {
  const [sql, setSql] = useState<string>('SELECT point_code, point_type, url\nFROM image_records\nWHERE created_at > "2024-01-01";');
  const [jsonOutput, setJsonOutput] = useState<string | null>(null);
  const [isRunning, setIsRunning] = useState(false);

  const handleRunSql = () => {
    if (!sql.trim().toLowerCase().startsWith('select')) {
        setStatusMessage("错误: 只允许执行 'SELECT' 开头的SQL语句。");
        return;
    }
    setIsRunning(true);
    setStatusMessage("正在连接数据库并执行查询...");
    
    // Simulate backend call
    setTimeout(() => {
        const formattedJson = MOCK_DB_RESPONSE.map(row => ({
            image: row
        }));
        setJsonOutput(JSON.stringify(formattedJson, null, 2));
        setStatusMessage(`查询成功！获取了 ${MOCK_DB_RESPONSE.length} 条记录。`);
        setIsRunning(false);
    }, 1500);
  };
  
  const handleDownloadJson = () => {
    if (!jsonOutput) return;
    const blob = new Blob([jsonOutput], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `training_data_${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    setStatusMessage('JSON文件已开始下载。');
  };

  const clearState = useCallback(() => {
    setSql('');
    setJsonOutput(null);
    setStatusMessage("状态: 空闲");
  }, [setStatusMessage]);

  return (
    <div className="p-4 flex flex-col gap-4 h-full">
      <Panel title="SQL查询以生成数据">
        <div className="flex gap-4 items-center mb-4">
            <Button onClick={handleRunSql} disabled={isRunning} icon={<PlayIcon className="w-4 h-4"/>}>运行SQL</Button>
            <Button onClick={clearState} disabled={isRunning} icon={<TrashIcon className="w-4 h-4"/>}>清空</Button>
            <p className="text-sm text-yellow-400">注意: 仅支持 'SELECT' 语句。</p>
        </div>
        <textarea
          value={sql}
          onChange={(e) => setSql(e.target.value)}
          placeholder="在此输入您的 SELECT SQL 语句..."
          className="w-full h-48 p-2 font-mono text-sm bg-black/70 border border-green-500/50 text-green-300 rounded-sm focus:outline-none focus:ring-2 focus:ring-cyan-500 hacker-scrollbar"
        />
      </Panel>
      
      <Panel title="生成的JSON" className="flex-grow flex flex-col">
        <div className="flex items-center mb-4">
            <Button onClick={handleDownloadJson} disabled={!jsonOutput}>下载JSON文件</Button>
        </div>
        <textarea
          value={jsonOutput ?? "// SQL执行结果将显示在此处"}
          readOnly
          className="w-full flex-grow p-2 font-mono text-sm bg-black/70 border border-green-500/50 text-cyan-200 rounded-sm focus:outline-none hacker-scrollbar"
        />
      </Panel>
    </div>
  );
};

export default GenerateJsonView;
